package com.starblink.postvideo.ui

import android.os.Bundle
import android.view.ViewTreeObserver
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.android.basic.util.post.PostListDataHolder
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.behavior.PagerStartSnapHelper
import com.starblink.basic.util.FilesUtils
import com.starblink.feedback.ui.PostMoreDialog
import com.starblink.novice_guide.SkNoviceGuideColl
import com.starblink.postvideo.databinding.ActivityVideoDetialBinding
import com.starblink.product.R
import com.starblink.product.controller.PostVideoController
import com.starblink.product.controller.VideoRenderViewFactory
import com.starblink.product.databinding.ItemRecommendVideoDetail2Binding
import com.starblink.product.detail.postrecommend.VideoDetailHolder
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.PostF
import com.starblink.rocketreserver.fragment.Poster
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.video.player.SingleVideoView
import com.starblink.video.player.VideoView
import com.starblink.video.util.VideoUtils
import com.starblink.videocache.cache.PreloadManager

@Route(path = RoutePage.PostVideo.PAGE_VIDEO)
class VideoDetailTVMActivity : BaseTVMActivity<ActivityVideoDetialBinding, VideoDetailVM>() {

    override fun initViewBinding(): ActivityVideoDetialBinding =
        ActivityVideoDetialBinding.inflate(layoutInflater)

    //    @Autowired(name = RoutePage.Post.POST_LIST)
    @JvmField
    var listPostMain: List<PostF>? = null

    @Autowired(name = RoutePage.Post.POST_ID)
    @JvmField
    var postId: String? = null//传进来的初始postId

    @Autowired(name = RoutePage.Post.POST)
    @JvmField
    var post: PostF? = null

    @Autowired(name = RoutePage.Post.ARG_SCENE)
    @JvmField
    var scene: Int = 0//前置进入场景

    @Autowired(name = RoutePage.Post.POST_PAGE)
    @JvmField
    var searchPageNo: Int = 0//其它场景加载页数

    @Autowired(name = RoutePage.Post.TOPIC_ID)
    @JvmField
    var topicId: String = ""//话题跳转id

    var currentIndex = 0

    var isSingle = true//是否是单一视频

//    lateinit var mAdapter: VideoDetailsAdapter

    lateinit var mPreloadManager: PreloadManager

    lateinit var layoutManager: LinearLayoutManager

    private lateinit var mController: PostVideoController

    lateinit var mVideoView: VideoView

    var mountedIsOpen = false//挂载商品弹窗是否打开

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.resultList.value!!).apply {
            addVhDelegate {
                VideoDetailHolder(
                    ItemRecommendVideoDetail2Binding.inflate(it.inflater, it, false),
                    mActivity as AppCompatActivity,
                    spmPageValue = SpmPageDef.VideoDetailRoute,
                    pageTrackTag = this.hashCode().toString(),
                    isFromFeeds = viewModel.resultList.value!!.size == 1 || isSingle,
                    guideCall = { bind ->
                        handleFlowBus(bind)
                    },
                    onSearchPicClick = {
                        screenShot()
                    },
                    shareCallBack = { id ->
                        viewModel.sharePost(id)
                    },
                    showMountedDialog = {
                        mountedIsOpen = true
                        mVideoView.pause()
                    },
                    dismissMountedDialog = {
                        mountedIsOpen = false
                        mVideoView.resume()
                    }
                )
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarWhiteText()

        initViewPager()
        initVideoView()
        initPostData()
        startObserve()

        postId?.let { viewModel.getPostDetail(it, currentIndex) }

        syncMountedProductState()

        viewBinding.vBackIcon.setOnClickListener {
            finish()
        }

        viewBinding.ivMoreIcon.setOnClickListener {
            if (viewModel.resultList.value != null) {
                PostMoreDialog(
                    this,
                    supportFragmentManager,
                    viewModel.resultList.value!![currentIndex]
                ).show(
                    supportFragmentManager,
                    "more"
                )
            }
        }
    }

    /**
     * 初始内容数据
     */
    private fun initPostData() {
        viewModel.originalPostId = postId.toString()

        if (scene == RoutePage.Post.SCENE.Discover.value || scene == RoutePage.Post.SCENE.SEARCH.value || scene == RoutePage.Post.SCENE.TOPIC.value) {
            listPostMain = PostListDataHolder.getInstance().getList()
        }
        if (listPostMain != null) {
            isSingle = false

            if (searchPageNo != 0) {
                viewModel.scenePageNo = searchPageNo
                viewModel.sceneId = topicId
            }
            //过滤视频数据
            var list = listPostMain!!.filter {
                it.contentType == "2"
            } as ArrayList<PostF>
            if (list.size > 0) {
                currentIndex = list.indexOfFirst { it.id == postId }
                if (currentIndex < 0) currentIndex = 0
                initData(list)

                if (currentIndex >= (viewModel.resultList.value?.size ?: 0) - 1) {
                    viewModel.getRecommend(scene)
                }

//                viewBinding.vp.adapter = mAdapter
//                viewBinding.rv.setCurrentItem(mCurPos, false)
                setCurrentItem()
            }
        } else {
            if (post != null) {
                viewModel.resultList.value!!.add(post!!.toJson().toBean<PostD>())
                viewModel.resultList.value = viewModel.resultList.value
//                viewModel.mList.value = arrayListOf(post!!.toJson().toBean<PostD>())
            } else {
                if (!postId.isNullOrEmpty()) {
                    //                    showStateLoading()
                }
            }
            postId?.let { viewModel.getPostDetail(it, 0) }
        }
    }

    private fun setCurrentItem() {
        if (currentIndex > 0) {
            viewBinding.rv.scrollToPosition(currentIndex)
            val manager: LinearLayoutManager = viewBinding.rv.layoutManager as LinearLayoutManager
            manager.scrollToPositionWithOffset(currentIndex, 0)
        }
    }

    private fun initData(
        postList: ArrayList<PostF>
    ) {
        var list = arrayListOf<PostD>()
        postList.forEach { post ->
            var imgUrl = post.mainPic
            ImageUtils.preloadImage(commContext(), imgUrl)
            var item: PostD = post.toJson().toBean<PostD>()

            list.add(item)
        }
        if (list.isNotEmpty()) {
            viewModel.resultList.value?.addAll(list)
            viewModel.resultList.value = viewModel.resultList.value
        }
    }

    private fun initVideoView() {
        mVideoView = VideoView(this)
        mVideoView.setLifecycle(lifecycle)
        mVideoView.setLooping(true)

        //以下只能二选一，看你的需求
        mVideoView.setRenderViewFactory(VideoRenderViewFactory.create())
//        mVideoView.setScreenScaleType(VideoView.SCREEN_SCALE_MATCH_PARENT);
        mController = PostVideoController(this)
        mVideoView.setVideoController(mController)
        mPreloadManager = PreloadManager.getInstance(this)
    }

    private fun initViewPager() {
        layoutManager = LinearLayoutManager(this)
        viewBinding.rv.layoutManager = layoutManager
        viewBinding.refresher.setEnableRefresh(false)
        viewBinding.refresher.setEnableLoadMore(false)
        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.getRecommend(scene)
            viewBinding.refresher.finishLoadMore(5000)
        }

        viewBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            private var mCurItem = 0

            /**
             * VerticalViewPager是否反向滑动
             */
            private var mIsReverseScroll = false
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val position = layoutManager.findFirstVisibleItemPosition()

                    if (!isSingle) {
                        if (position == (viewModel.resultList.value?.size ?: 0) - 2) {
                            viewModel.getRecommend(scene)
                        }

                        if (viewModel.resultList.value != null && viewModel.resultList.value!!.size > position && !viewModel.idList.contains(
                                viewModel.resultList.value!![position].id
                            )
                        ) {
//                        Log.e("VideoDetailTVMActivity", "====getPostDetail===$pos")
                            viewModel.getPostDetail(
                                viewModel.resultList.value!![position].id,
                                position
                            )
                        }
                    }

                    if (position == currentIndex) return
                    startPlay(position)
                }
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    mCurItem = layoutManager.findFirstVisibleItemPosition()
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(currentIndex, mIsReverseScroll)
                } else {
                    mPreloadManager.pausePreload(currentIndex, mIsReverseScroll)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val position = layoutManager.findFirstVisibleItemPosition()
                if (position == mCurItem) {
                    return
                }
                mIsReverseScroll = position < mCurItem
            }
        })

    }

    private fun startObserve() {
        viewModel.resultList.observe(this) {
            if (it.isNotEmpty()) {
                if (viewBinding.rv.adapter == null) {
                    viewBinding.rv.adapter = adapter

                    val snapHelper = PagerStartSnapHelper()
                    snapHelper.attachToRecyclerView(viewBinding.rv)

                    viewBinding.rv.viewTreeObserver.addOnGlobalLayoutListener(object :
                        ViewTreeObserver.OnGlobalLayoutListener {
                        override fun onGlobalLayout() {
                            //因为onGlobalLayout可能会多次调用，所以记得移除监听
                            val width = viewBinding.rv.width
                            val height = viewBinding.rv.height
                            //通过调用view.getHeight()和view.getWidth()来判断view是否已经绘制好
                            if (width > 0 && height > 0) {
                                viewBinding.rv.viewTreeObserver.removeOnGlobalLayoutListener(this)
                            } else {
                                return
                            }
                            startPlay(currentIndex)
                        }
                    })
                } else {
                    adapter.notifyDataSetChanged()
                }
                if (!isSingle) {
                    viewBinding.refresher.setEnableLoadMore(true)
                }
            }
        }
    }

    ///播放视频
    private fun startPlay(position: Int) {
        val itemView = layoutManager.findViewByPosition(position)
        if (itemView != null) {
            val tiktokView: SingleVideoView = itemView.findViewById(R.id.tiktok_View)
            val tiktokBean: PostD = itemView.tag as PostD

            mVideoView.release()
            VideoUtils.removeViewFormParent(mVideoView)
            if (tiktokBean.pictures != null && tiktokBean.pictures!!.isNotEmpty()) {
                val playUrl = mPreloadManager.getPlayUrl(
                    tiktokBean.pictures?.get(0)?.pictureF?.picUrl
                        ?: ""
                )
                mVideoView.setUrl(playUrl)
                //请点进去看isDissociate的解释
                mController.addControlComponent(tiktokView, true)
                tiktokView.addView(mVideoView, 0)
//                Log.e(
//                    "VideoDetailTVMActivity",
//                    "===1111==${playUrl}"
//                )
                mVideoView.start()
            }
            currentIndex = position
        }
    }

    /**
     * 同步挂载商品状态
     */
    private fun syncMountedProductState() {
        //同步关注状态
        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                if (post.posterInfo != null && post.posterInfo.poster.id == event.id && event.relationCode != post.posterInfo.poster.relationCode) {
                    val poster = post.posterInfo.poster
                    ApolloValSetExt.setApolloVal<Poster>(
                        poster,
                        "relationCode",
                        event.relationCode
                    )
                    viewModel.resultList.value!![index] = post
                    viewModel.resultList.value = viewModel.resultList.value
                    break
                }
            }
        }

        //同步点赞状态
        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                if (post.id == event.postId && event.like != post.liked) {
                    ApolloValSetExt.setApolloVal<PostD>(
                        post,
                        "liked",
                        event.like
                    )
                    viewModel.resultList.value!![index] = post
                    viewModel.resultList.value = viewModel.resultList.value
                    break
                }
            }
        }

        //同步挂载商品订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                val productList = post.productList
                if (productList != null && productList.isNotEmpty()) {
                    for (item in productList) {
                        var it = item.productF
                        if (it.merchantWeb != null && it.merchantWeb!!.id == event.id && event.followed != it.merchantWeb!!.subOrNot) {
                            val merchant = it.merchantWeb!!
                            ApolloValSetExt.setApolloVal<ProductF.MerchantWeb>(
                                merchant,
                                "subOrNot",
                                event.followed
                            )
                            viewModel.resultList.value!![index] = post
                            viewModel.resultList.value = viewModel.resultList.value
                            break
                        }
                    }
                }
            }
        }

        //同步挂载商品收藏状态
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            for (index in viewModel.resultList.value?.indices!!) {
                val post = viewModel.resultList.value!![index]
                val productList = post.productList
                if (productList != null && productList.isNotEmpty()) {
                    for (item in productList) {
                        var it = item.productF
                        if (it.id == event.id && event.collect != it.collected) {
                            ApolloValSetExt.setApolloVal<ProductF>(
                                it,
                                "collected",
                                event.collect
                            )
                            viewModel.resultList.value!![index] = post
                            viewModel.resultList.value = viewModel.resultList.value
                            break
                        }
                    }
                }
            }
        }
    }

    /**
     * 截图识图
     */
    private fun screenShot() {
        viewModel.resultList.value ?: return
        val played = mVideoView.currentPosition > 0
        val bitmap = mVideoView.doScreenShot()
        val index = if (currentIndex < viewModel.resultList.value!!.size) currentIndex else 0
        if (bitmap != null && played) {
            val path = FilesUtils.getInstance().saveBitmap(
                bitmap,
                "video_${viewModel.resultList.value!![index].id}_${System.currentTimeMillis()}"
            )
            this.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                withString(RoutePage.ImageSearch.ARGS_FILE_PATH, path)
            }
        } else {
            this.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                withString(
                    RoutePage.ImageSearch.ARGS_IMG_URL,
                    viewModel.resultList.value!![index].mainPic
                )
            }
        }
    }


    var hasShowGuide = false
    private fun handleFlowBus(binding: ItemRecommendVideoDetail2Binding) {
        /**
         * 显示下滑引导
         */
        if (!hasShowGuide) {
            hasShowGuide = true
            binding.includeRight.ivSearch.post {
                SkNoviceGuideColl.handleVideoImgSearch(
                    this,
                    binding.includeRight.ivSearch,
                    binding.root
                ) {
                    screenShot()
                }
            }
            FlowBus.with<Boolean>(SkGuideEnum.POST_VIDEO_DOWN.name).register(this) {
                if (it) {
                    val downTimer = FlowCountDownTimer(time = 1)
                    downTimer.start(callBack = {
                        binding.container.post {
                            SkNoviceGuideColl.handleVideoPop(
                                this,
                                binding.container,
                                binding.root, 0
                            )
                        }
                        downTimer.cancel()
                    }, onFinish = {
                    })
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (mVideoView != null && !mountedIsOpen) {
            mVideoView.resume()
        }
        pageExposure(
            SpmPageDef.VideoDetailRoute,
            params = mapOf("itemId" to (postId ?: ""), "contentType" to "2")
        )
    }

    override fun onPause() {
        pageDisappear(
            SpmPageDef.VideoDetailRoute,
            params = mapOf("itemId" to (postId ?: ""), "contentType" to "2")
        )
        super.onPause()
        if (mVideoView != null) {
            mVideoView.pause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mVideoView != null) {
            mVideoView.release()
        }
        mPreloadManager.removeAllPreloadTask()
    }
}